<?php
/**
 * 后台模块管理
 *
 * 后台模块管理(目前只有发现页)
 *
 * @author    zhouchao <zhouchao@yunys.com.cn>
 * @copyright 2016 QuanZhouYunYiShang Inc.
 */
namespace App\Http\Controllers\Backstage;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Services\FindModuleService\FindModuleBackstageService;
use Illuminate\Support\Facades\Response;
use App\Services\BrandService\BrandToolService;
use App\Services\UserService\UserTool;
use App\Services\ProductTempService\ProductTempTool;
use App\Services\TypesService\TypesBackService;

class ModuleController extends Controller
{
    protected $find_module_backstage_service;
    protected $user_tool;
    public function __construct(FindModuleBackstageService $find_module_backstage_service,BrandToolService $brand_tool_service,UserTool $user_tool,ProductTempTool $productTempTool)
    {
        $this->find_module_backstage_service = $find_module_backstage_service;
        $this->brand_tool_service = $brand_tool_service;
        $this->user_tool = $user_tool;
        $this->productTempTool = $productTempTool;
    }

    /**
     * 获取已添加的模块
     */
    public function getModuleList()
    {
        //获取
        $find_modules = $this->find_module_backstage_service->getList();
        return view('backstage.module.module_list')->with(['find_modules'=>$find_modules]);
    }

    /**
     * 修改显示状态
     * @param Request $request
     * @return mixed
     */
    public function postShow(Request $request)
    {
        $is_show = intval($request->input('is_show')) == 1 ? 1 : 0;
        $find_module_id = intval($request->input('find_module_id'));
        $result = $this->find_module_backstage_service->update_module_by_id($find_module_id,array('is_show'=>$is_show,'updated_at'=>time()));
        $result = empty($result) ? $this->find_module_backstage_service->createResult('M00003',(object)array()) :
            $this->find_module_backstage_service->createResult('M00000',array('is_show'=>$is_show));
        return Response::json($result);
    }

    /**
     * 删除模块
     * @param Request $request
     * @return mixed
     */
    public function postDelete(Request $request)
    {
        $find_module_id = intval($request->input('find_module_id'));
        $result = $this->find_module_backstage_service->delete_module_resources($find_module_id,array('state'=>2,'updated_at'=>time()));
        $result = empty($result) ? $this->find_module_backstage_service->createResult('M00003',(object)array()) :
            $this->find_module_backstage_service->createResult('M00000',(object)array());
        return Response::json($result);
    }

    /**
     * 修改排序
     * @param Request $request
     * @return mixed
     */
    public function postUpdateSort(Request $request)
    {
        $sort = intval($request->input('sort')) == 0 ? 999 : intval($request->input('sort'));
        $find_module_id = intval($request->input('find_module_id'));
        $result = $this->find_module_backstage_service->update_module_by_id($find_module_id,array('sort'=>$sort,'updated_at'=>time()));
        $result = empty($result) ? $this->find_module_backstage_service->createResult('M00003',(object)array()) :
            $this->find_module_backstage_service->createResult('M00000',array('sort'=>$sort));
        return Response::json($result);
    }

    /**
     * 更新资源排序
     * @param Request $request
     * @return mixed
     */
    public function postUpdateResourceSort(Request $request){
        $sort = intval($request->input('sort')) == 0 ? 999 : intval($request->input('sort'));
        $find_module_id = intval($request->input('find_module_id'));
        $resource_id = trim($request->input('resource_id'));
        $result = $this->find_module_backstage_service->update_module_resources_sort($find_module_id,$resource_id,array('sort'=>$sort,'updated_at'=>time()));
        $result = empty($result) ? $this->find_module_backstage_service->createResult('M00003',(object)array()) :
            $this->find_module_backstage_service->createResult('M00000',array('sort'=>$sort));
        return Response::json($result);
    }

    /**
     * 添加模块页面
     * @param Request $request
     * @return $this
     */
    public function getAddModule(Request $request)
    {
        $relate_modules = $this->find_module_backstage_service->get_all_relate_modules();
        return view('backstage.module.add_module')
            ->with(['relate_modules'=>$relate_modules]);
    }

    /**
     * 添加模块
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function postAddModule(Request $request){
        $this->validate($request,[
            'find_module_name'=>'required|max:20|unique:find_modules,find_module_name',
            'redirect_module' => 'alpha_num|max:32'
        ]);
        $find_module_name = trim($request->input('find_module_name'));
        if(empty($find_module_name)){
            return redirect()->back()->with('error_message','请输入模块名称');
        }
        $app_id = intval($request->input('app_id'));
        $app_name = $this->find_module_backstage_service->getAppNameByAppid($app_id);
        if($app_name == false){
            return redirect()->back()->with('error_message','请选择正确的关联模块');
        }
        $redirect_module = $request->input('redirect_module');
        if(empty($redirect_module)){
            $redirect_module = 0;
        }
        $result = $this->find_module_backstage_service->save_module(array('find_module_name'=>$find_module_name,'app_id'=>$app_id,'redirect_module'=>$redirect_module));
        return empty($result) ? redirect()->back()->with('error_message','操作失败') : redirect('backstage/module/module-list')->with('success_message','成功');
    }

    /**
     * 编辑模块页面
     * @param $module_id
     * @return $this|\Illuminate\Http\RedirectResponse
     */
    public function getUpdate($module_id)
    {
        $this->find_module_backstage_service->setParameter([
            'table' => 'find_modules',
            'where' => [['find_module_id','=',intval($module_id)]],
            'select'=> ['find_module_id','find_module_name','app_id','is_show']
        ]);
        $module = $this->find_module_backstage_service->getById();
        if(empty($module)){
            return redirect()->back()->with('error_message','未找到该模块');
        }
        $relate_modules = $this->find_module_backstage_service->get_all_relate_modules();
        return view('backstage.module.update_module')
            ->with(['relate_modules'=>$relate_modules,'module'=>$module]);
    }

    /**
     * 更新模块
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function postUpdate(Request $request){
        $this->validate($request,[
            'find_module_id' => 'required|integer',
            'find_module_name'=>'required|max:20|unique:find_modules,find_module_name,'.intval($request->input('find_module_id')).',find_module_id'
        ]);
        $find_module_id = intval($request->input('find_module_id'));
        $find_module_name = trim($request->input('find_module_name'));
        if(empty($find_module_name)){
            return redirect()->back()->with('error_message','请输入模块名称');
        }
        $result = $this->find_module_backstage_service->update_module_by_id($find_module_id,array('find_module_name'=>$find_module_name,'updated_at'=>time()));
        return empty($result) ? redirect()->back()->with('error_message','操作失败') : redirect('backstage/module/module-list')->with('success_message','成功');
    }

    /**
     * 添加数据
     * @param $id
     * @return $this|\Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     */
    public function getAddData($id,TypesBackService $typesBackService,Request $request){
        $id = intval($id);
        $this->find_module_backstage_service->setParameter([
            'table' => 'find_modules',
            'where' => [['find_module_id','=',$id],['state','=',1]],
            'select'=> ['find_module_name','app_id','redirect_module']
        ]);
        $find_module = $this->find_module_backstage_service->getById();
        if(empty($find_module)){
            return redirect()->back()->with('error_message','未找到模块');
        }
        if($find_module->app_id == 1){
            //轮播图
            return redirect()->back();
        }elseif($find_module->app_id == 10){
            return redirect()->back();
        }elseif($find_module->app_id == 2){
            //推荐设计师
            $input = $request->input('conditions');
            if(!empty($input)){
                $input = json_decode($input);
                if(empty($input)){
                    return redirect()->back()->with('error_mesage','未找到符合条件的设计师');
                }
                $conditions = (array)$input;
                $conditions['user_type'] = isset($conditions['user_type']) ? $conditions['user_type'] : 1;
                if(!isset($conditions['user_param']) || empty($conditions['user_param'])){
                    $users = $this->user_tool->getAuthticationUser($conditions['user_type']);
                }else{
                    $users = $this->user_tool->searchUser($conditions['user_param'],$conditions['user_type']);
                }
            }else{
                $users = $this->user_tool->getAuthticationUser(1);
            }
            return view('backstage.module.add_data_users')
                ->with('find_module_id',$id)
                ->with('app_id',$find_module->app_id)
                ->with('users',$users)
                ->with('conditions',$input);
        }elseif($find_module->app_id == 3){
            //产品
            $brands = $this->brand_tool_service->getAllBrands();
            $product_temp_categorys = $this->productTempTool->getAllProductTempCategorys(1);
            //array_unshift($product_temp_categorys,(object)array('name'=>'全部','product_temp_category_id'=>0));
            $input = $request->input('conditions');
            if(!empty($input)){
                $input = json_decode($input);
                if(empty($input)){
                    return redirect()->back()->with('error_mesage','未找到符合条件的产品');
                }
                $products = $typesBackService->get_search_product_list((array)$input);
            }else{
                $products = $typesBackService->get_search_product_list(array('user_type' => '0','brand_id' => '0',
                    'is_shelves' => '-1','user_param' => '0','product_id' => '0','product_temp_category_id' => $find_module->redirect_module));
            }
            return view('backstage.module.add_data_product')
                ->with(['find_module_id'=>$id,'brands'=>$brands,
                    'product_temp_categorys'=>$product_temp_categorys,'redirect_module'=>$find_module->redirect_module,
                    'app_id'=>$find_module->app_id,'products'=>$products,'conditions'=>$input]);
        }elseif($find_module->app_id == 4){
            //主题
            $types = $this->find_module_backstage_service->get_type_by_module_id($id);
            return view('backstage.module.add_data_type')
                ->with(['find_module_id'=>$id,'types'=>$types,'app_id'=>$find_module->app_id]);
        }else{
            //推荐品牌商
            $input = $request->input('conditions');
            if(!empty($input)){
                $input = json_decode($input);
                if(empty($input)){
                    return redirect()->back()->with('error_mesage','未找到符合条件的设计师');
                }
                $conditions = (array)$input;
                $conditions['user_type'] = isset($conditions['user_type']) ? $conditions['user_type'] : 1;
                if(!isset($conditions['user_param']) || empty($conditions['user_param'])){
                    $users = $this->user_tool->getAuthticationUser($conditions['user_type']);
                }else{
                    $users = $this->user_tool->searchUser($conditions['user_param'],$conditions['user_type']);
                }
            }else{
                $users = $this->user_tool->getAuthticationUser(2);
            }
            return view('backstage.module.add_data_users')
                ->with('find_module_id',$id)
                ->with('app_id',$find_module->app_id)
                ->with('users',$users)
                ->with('conditions',$input);
        }

    }

    /**
     * 添加数据
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function postAddData(Request $request){
        $data_ids = $request->input('data_ids');
        if(empty($data_ids)){
            return redirect()->back()->with('error_message', '请至少选择一项');
        }
        $find_module_id = intval($request->input('find_module_id'));
        $this->find_module_backstage_service->module_add_data($find_module_id,$data_ids);
        return redirect()->back()->with('success_message','添加成功');
    }

    /**
     * 获取数据列表
     * @param $id
     * @return $this|\Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     */
    public function getDataList($id){
        $id = intval($id);
        $this->find_module_backstage_service->setParameter([
            'table' => 'find_modules',
            'where' => [['find_module_id','=',$id],['state','=',1]],
            'select'=> ['find_module_name','app_id']
        ]);
        $find_module = $this->find_module_backstage_service->getById();
        if(empty($find_module)){
            return redirect()->back()->with('error_message','未找到模块');
        }
        //获取所有的模块
        $find_modules = $this->find_module_backstage_service->getList();
        $datas = $this->find_module_backstage_service->get_module_data_list($find_module->app_id,$id);
        if($find_module->app_id == 1){
            return redirect()->back();
        }elseif($find_module->app_id == 10){
            return redirect()->back();
        }elseif($find_module->app_id == 2){
            //推荐设计师
            return view('backstage.module.data_user_list')
                ->with(['find_modules'=>$find_modules,'find_module_id'=>$id,'users'=>$datas]);
        }elseif($find_module->app_id == 3){
            //产品
            return view('backstage.module.data_product_list')
                ->with(['find_modules'=>$find_modules,'find_module_id'=>$id,'products'=>$datas]);
        }elseif($find_module->app_id == 4){
            //主题
            return view('backstage.module.data_type_list')
                ->with(['find_modules'=>$find_modules,'find_module_id'=>$id,'types'=>$datas]);
        }else{
            //推荐品牌商
            return view('backstage.module.data_user_list')
                ->with(['find_modules'=>$find_modules,'find_module_id'=>$id,'users'=>$datas]);
        }
    }

    /**
     * 搜索用户
     * @param Request $request
     * @return mixed
     */
    public function postSearchUser(Request $request){
        $user_type = intval($request->input('user_type'));
        $user_param = trim($request->input('user_param'));
        if(empty($user_param)){
            $users = $this->user_tool->getAuthticationUser($user_type);
        }else{
            $users = $this->user_tool->searchUser($user_param,$user_type);
        }
        return Response::json($users);
    }

    /**
     * 删除资源
     * @param $module_id
     * @param $resource_id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function getDeleteResource($module_id,$resource_id){
        $result = $this->find_module_backstage_service->delete_resource(intval($module_id),$resource_id);
        return empty($result) ? redirect()->back()->with('error_message','删除失败') : redirect()->back()->with('success_message','删除成功');
    }

    /**
     * 查找模板分类
     * @return array
     */
    public function postSearchCategorys(){
        //获取模板分类
        $product_temp_categorys = $this->productTempTool->getAllProductTempCategorys(1);
        //array_unshift($product_temp_categorys,(object)array('name'=>'全部','product_temp_category_id'=>0));
        return $product_temp_categorys;
    }
}
